<template>
  <div class="header-write-input-process">
    <span>{{ $i18n('common.workflow.label') }}：</span>
    <div class="input-process-box" :class="{'input-process-box-active': isActive, 'input-process-box-readonly': isShowReadOnly}">
      <template v-if="!isView && !tokenInputDestroy">
        <TokenInputPeople
          :placeholder="workflowInfo.workflowNodesInfo.tipTitle"
          @changeActive="changeActive"
          @afterSelectPeople="afterSelectPeople"
          ref="tokenInputRef" />
      </template>
      <template v-else>
        <a-tooltip :title="workflowInfo.workflowNodesInfo.value" placement="bottom">
          <a-input
            :value="workflowInfo.workflowNodesInfo.value"
            :disabled="workflowInfo.workflowNodesInfo.disabled"
            :readOnly="workflowInfo.workflowNodesInfo.readOnly"
            :placeholder="workflowInfo.workflowNodesInfo.tipTitle"
            class="work-flow"
            style="border: none"
            @click="isEditWorkflow ? editWorkflow() : ''" />
        </a-tooltip>
      </template>
        <span
          class="btn-text"
          @click="isEditWorkflow ? editWorkflow() : showWorkflow()"
          >{{ workflowInfo.workflowButton.name }}</span
        >
    </div>
  </div>
</template>

<script>
  /*global _ctxPath, loadAndRefreshPrediction, _getZWIframe, workflowModule*/
  import TokenInputPeople from '@/components/token-input-people';
  import { useBaseInfoStore } from '@/store/modules/base-info.js';
  import { useSrcCacheStore } from '@/store/modules/src-cache';
  import { mapState, mapActions } from 'pinia';
  import globalMethods from '@/plugins/methods';
  import api from '@/api';
  import emitter from '@/plugins/global-callback';
  import { getWorkflowTransParams } from '@/helper/workflow-helper';
  export default {
    name: 'headerBtns',
    props: {},
    data() {
      return {
        //快速选人销毁状态，编辑流程后就不能再使用了
        tokenInputDestroy: false,
        isActive: false
      };
    },
    mounted() {
      this.initTokenInputPeople();
    },
    components: {
      TokenInputPeople
    },
    created() {
      this.api = api;
      //订阅自由协同的发送事件
      emitter.subscribe('sendFreeCol', this.parse2ProcessXml);
      emitter.subscribe('insertNode', ()=>this.tokenInputDestroy=true);
    },
    computed: {
      ...mapState(useBaseInfoStore, ['baseInfo', 'attachments', 'formInfo']),
      // 流程
      workflowInfo() {
        return this.formInfo.workflowInfo;
      },

      businessData() {
        return this.formInfo.businessData;
      },
      //是否是编辑流程
      isEditWorkflow() {
        return this.workflowInfo?.workflowButton?.canEditWorkflow === true;
      },
      //标题下方的流程是预览模式还是可编辑的快速选人模式
      isView() {
        return this.workflowInfo?.workflowButton?.isView === true;
      },
      //是否是自由协同
      isFreeCol() {
        return this.baseInfo?.zwIframe?.freeCol === true;
      },
      isShowReadOnly() {
        return !(!this.isView && !this.tokenInputDestroy) && this.workflowInfo.workflowNodesInfo.readOnly;
      }
    },
    methods: {
      ...mapActions(useSrcCacheStore, ['createShowWorkFlowUrl', 'createEditWorkFlowUrl']),
      ...mapActions(useBaseInfoStore,['updateWorkflowNodesInfo']),

      showWorkflow() {
        if (window._executePrediction != this._executePrediction) {
          window._executePrediction = this._executePrediction;
        }

        //查看流程
        const dialog = globalMethods.dialog({
          url: this.createShowWorkFlowUrl(),
          id: 'workflow_dialog_workflowDesigner_Id',
          title: this.$i18n('workflow.designer.title.readonly'),
          transParams: getWorkflowTransParams(),
          footer: null,
          width: window.innerWidth * 0.9,
          height: window.innerHeight * 0.95 - 55,
          centered: true,
          dialogStyle: {
            'padding-bottom': 0,
            'margin': '0 !important',
            'max-height': '100%',
            'max-width': '95%',
          },
          bodyStyle: {
            padding: 0,
            overflow: 'auto',
            'max-height': 'calc(100vh - 55px)',
          },
          dialogClass: 'workflow-dialog-container',
          onCancel() {
            dialog.close();
          }
        });
      },
      _executePrediction(dialogMode) {
        // loading 效果
        if (dialogMode != true) {
          $('#prediction_body').html(
            '<img class="center_img" src="' +
              _ctxPath +
              '/common/workflow/simulation/img/loading.gif">'
          );
        }

        // 刷新数据, loadAndRefreshPrediction 定义在 workflowPrediction.jsp
        loadAndRefreshPrediction({
          container: '#prediction_body',
          contentAPI: _getZWIframe().contentAPI,
          summaryId: this.businessData.summary.id,
          formId: this.businessData.template.formAppId,
          templateId: this.businessData.template.id,
          processId: this.businessData.workflow.processId,
          currentNodeId: 'start',
          showType: dialogMode === true ? 'dialog' : ''
        });
      },
      async parse2ProcessXml() {
        //已经生成就不用再处理了
        if (this.tokenInputDestroy || this.isView) {
          return;
        }
        let processXml = document.querySelector('#process_xml');
        processXml.value = '';
        let parseObj = await this.$refs.tokenInputRef.findSelectPeopleEntities();
        const {
          id: userId,
          name: userName,
          loginAccount,
          loginAccountName
        } = this.businessData.currentUser;
        const { defaultNodeName, defaultNodeLable } = this.businessData.nodePolicy;
        console.log(" this.businessData.nodePolicy;",  this.businessData.nodePolicy)
        const token_flowType = this.$refs.tokenInputRef.tokenFlowType; ///流程类型,默认1并发 并发，串发； 多层 快速录入不支持
        //把选人信息解析成xml写入到页面的#process_xml
        window.createProcessXmlCallBack(
          window,
          { obj: [parseObj, token_flowType] },
          'collaboration',
          window,
          userId,
          userName,
          loginAccountName,
          defaultNodeName,
          loginAccount,
          defaultNodeLable,
          "createProcessXml",
          "default"
        );
      },
      /**
       * @description: 编辑流程
       * @return {*}
       */
      async editWorkflow() {
        const { name } = this.workflowInfo.workflowButton;
        const { workflowNodesInfo } = this.workflowInfo;
        await this.parse2ProcessXml();
        let disableTokenInput = () => (this.tokenInputDestroy = true);
        const dialog = globalMethods.dialog({
          url: this.createEditWorkFlowUrl(),
          id: 'workflow_dialog_workflowDesigner_Id',
          title: name,
          width: window.innerWidth * 0.9,
          height: window.innerHeight * 0.95 - 108,
          centered: true,
          dialogStyle: {
            'padding-bottom': 0,
            'margin': '0 !important',
            'max-height': '100%',
            'max-width': '95%',
          },
          bodyStyle: {
            padding: 0,
            overflow: 'auto',
            'max-height': 'calc(100vh - 108px)',
          },
          dialogClass: 'workflow-dialog-container',
          transParams: getWorkflowTransParams(),
          onCancel() {
            dialog.close();
          },
          onConfirm:()=> {
            const result = dialog.getValue({
              innerButtonId: 'ok',
              checkXML: false
              // checkXML: d.immediatelySave == true,
              // checkCallback: u,
            });
            if (result === false) {
              return;
            }
            console.log(result);
            workflowModule.setWorkflowParams(result);
            //快速选人值回填
            this.updateWorkflowNodesInfo(result[2]);
            disableTokenInput();
            // disableTokenInput();
            dialog.close();
            // dialog.close();
          }
        });
      },
      initTokenInputPeople() {
        let conversionInfo = this.baseInfo.conversionInfo;
        if (conversionInfo && conversionInfo.peopleCardInfo) {
          this.tokenInputDestroy = true;
          const {
            id: userId,
            name: userName,
            loginAccount,
            loginAccountName
          } = this.businessData.currentUser;
          const { defaultNodeName, defaultNodeLable } = this.businessData.nodePolicy;

          let aPeople = {
            id: conversionInfo.peopleCardInfo.id,
            name: conversionInfo.peopleCardInfo.name,
            type: 'Member',
            excludeChildDepartment: false,
            accountId: conversionInfo.peopleCardInfo.orgAccountId
          };

          let personArrays = [];
          let obj = [personArrays, 1, false];
          aPeople.accountShortname = ''; // 不显示

          personArrays.push(aPeople);
          let res = {
            obj: obj
          };
          window.createProcessXmlCallBack(
            window,
            res,
            'collaboration',
            window,
            userId,
            userName,
            loginAccountName,
            defaultNodeName,
            loginAccount,
            defaultNodeLable
          );
          this.workflowInfo.workflowNodesInfo.value = `${conversionInfo.peopleCardInfo.name}(${defaultNodeLable})`;
        }
      },
      changeActive(value) {
        this.isActive = value;
      },
      afterSelectPeople({tokenFlowType}){
        //多层模式，需要弹出dialog弹窗
        if (tokenFlowType == 2){
          if (this.isEditWorkflow){
            this.editWorkflow();
          }
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .header-write-input-process {
    display: flex;
    align-items: center;
    span {
      color: #333;
      font-size: 14px;
      &:first-child {
        width: 64px;
        text-align: right;
      }
      &.btn-text {
        display: inline-block;
        text-wrap: nowrap;
        padding-left: 30px;
        padding-right: 20px;
        line-height: 16px;
        font-size: 14px;
        color: #1890ff;
        color: var(--theme-brand6,#1890ff);
        border-left: 1px solid #e4e4e4;
        word-break: keep-all;

        &:hover {
          cursor: pointer;
          color: #40a9ff;
          color: var(--theme-brand4, #40a9ff);
        }
      }
      &.icon-xuanren {
        margin-right: 30px;
        margin-left: 10px;
        i {
          color: #666;
          font-size: 14px;
        }
      }
    }
    .input-process-box {
      flex: 1;
      display: flex;
      align-items: center;
      border: 1px solid #d9d9d9;
      background-color: #fff;
      // height: 32px;
      box-sizing: border-box;
      overflow: hidden;
      border-radius: 3px;
      &:hover, &-active {
        border-color: #40a9ff;
        border-color: var(--theme-brand4, #40a9ff);
      }
      &-readonly {
        border: 1px solid #d9d9d9 !important;
      }
    }
    input.work-flow {
      border: none;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    .ant-input-disabled:focus,
    .ant-input-disabled:hover {
      box-shadow: none;
    }
  }
</style>
<style>
  .input-process-box {
    .ant-select-selection--multiple {
      min-height: 30px;
    }
    .token-input-people .ant-select-selection--multiple .ant-select-selection__rendered {
      max-height: 30px;
    }
    .token-input-people div.ant-select-selection--multiple {
      max-height: 30px;
    }
  }

  .workflow-dialog-container .modal-iframe-wrapper {
    min-width: 600px;
  }
</style>